package cn.royan.fl.proxys 
{
	import cn.royan.fl.ClientSocket;
	import cn.royan.fl.events.SocketEvent;
	import cn.royan.fl.utils.Logger;
	import cn.royan.fl.SocketFacade;
	import cn.royan.fl.events.NetworkEvent;
	import cn.royan.fl.values.ClientConfig;
	import cn.royan.fl.services.ClientSocketProtocol;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	/**
	 * ...
	 * @author RoYan
	 */
	public class ClientSocketProxy extends Proxy implements IProxy 
	{
		public static const NAME:String = "ClientSocketProxy";
		
		protected var client:ClientSocket;
		protected var socketProtocol:ClientSocketProtocol;
		
		public function ClientSocketProxy() 
		{
			super( ClientSocketProxy.NAME );
		}
		
		public function runClient( config:ClientConfig ):void
		{
			client = config.client;
			
			socketProtocol = new ClientSocketProtocol( config.host, config.port );
			socketProtocol.addEventListener( NetworkEvent.NETWORK_CONNECT, 	socketConnectHandler );
			socketProtocol.addEventListener( NetworkEvent.NETWORK_PACKET, 	socketPacketHandler );
			socketProtocol.addEventListener( NetworkEvent.NETWORK_CLOSE, 	socketCloseHandler );
			socketProtocol.addEventListener( NetworkEvent.NETWORK_ERROR, 	socketErrorHandler );
			socketProtocol.sendRequest();
			socketProtocol.connect();
			
			config.socketProtocol = socketProtocol;
			
			setData( config );
		}
		
		protected function socketConnectHandler( evt:NetworkEvent ):void
		{
			client.dispatchEvent( new SocketEvent( SocketEvent.SOCKET_CONNECT ) );
		}
		
		protected function socketPacketHandler( evt:NetworkEvent ):void
		{
			sendNotification( SocketFacade.PACKET_RECEIVE, evt.data );
		}
		
		protected function socketCloseHandler(evt:NetworkEvent):void
		{
			client.dispatchEvent( new SocketEvent( SocketEvent.SOCKET_CLOSE ) );
		}
		
		protected function socketErrorHandler(evt:NetworkEvent):void
		{
			client.dispatchEvent( new SocketEvent( SocketEvent.SOCKET_ERROR ) );
		}
	}

}